<template>
  <div v-if="showDialog" class="modal-overlay" @click="closeOnOverlay">
    <div class="modal-container" @click.stop>
      <div class="modal-header">
        <h2>选择学校</h2>
        <button class="close-button" @click="closeDialog">&times;</button>
      </div>
      <div class="modal-body">
        <div class="search-container">
          <input
            type="text"
            v-model="searchQuery"
            class="search-input"
            placeholder="请输入学校名称"
            @input="filterSchools"
            @focus="showDropdown = true"
          />
          <span class="search-icon">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="11" cy="11" r="8"></circle>
              <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
          </span>
          <div v-if="showDropdown && filteredSchools.length > 0" class="dropdown">
            <ul class="school-list">
              <li
                v-for="school in filteredSchools"
                :key="school._id"
                @click="selectSchool(school)"
                class="school-item"
              >
                {{ school.name }}
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button
          @click="submitSelection"
          class="submit-button"
          :disabled="!searchQuery"
        >
          确认选择
        </button>
        <p @click="closeDialog" class="redirect-text">稍后再选</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useStore } from '../stores/userStore'

const router = useRouter()
const store = useStore()

// 接收父组件传递的props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

// 定义事件用于通知父组件
const emit = defineEmits(['update:modelValue'])

// 本地状态，受props控制
const showDialog = ref(props.modelValue)
const schools = ref([]) // 存储学校数据
const filteredSchools = ref([]) // 存储过滤后的学校数据
const searchQuery = ref('') // 搜索框的输入内容
const selectedSchool = ref(null) // 存储选中的学校
const showDropdown = ref(false) // 控制下拉列表显示

// 监听props的变化
watch(() => props.modelValue, (newVal) => {
  showDialog.value = newVal
  // 如果打开对话框，重新加载学校数据
  if (newVal) {
    fetchSchools()
  }
})

// 获取学校数据
async function fetchSchools() {
  try {
    const response = await axios.get('http://localhost:5000/school')
    schools.value = response.data
    filteredSchools.value = response.data // 初始化为所有学校
    console.log('学校数据:', schools.value)
  } catch (error) {
    console.error('获取学校数据失败:', error)
  }
}

// 过滤学校
function filterSchools() {
  if (searchQuery.value) {
    filteredSchools.value = schools.value.filter(school =>
      school.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  } else {
    filteredSchools.value = schools.value
  }
  showDropdown.value = true
}

// 选择学校
function selectSchool(school) {
  store.user.school = school._id // 更新用户选择的学校ID而不是名称
  searchQuery.value = school.name
  selectedSchool.value = school
  showDropdown.value = false
}

// 提交选择
async function submitSelection() {
  if (!searchQuery.value || !selectedSchool.value) {
    alert('请先选择一所学校')
    return
  }

  if (confirm('学校选择后不可再更改，确定是这个学校吗？')) {
    const token = localStorage.getItem('token')
    try {
      // 获取当前用户信息
      const userResponse = await axios.get('http://localhost:5000/users/me', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
      const userId = userResponse.data._id

      // 提交学校ID到用户记录
      await axios.put('http://localhost:5000/users/me', { school: selectedSchool.value._id }, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })

      // 将用户ID添加到学校的users数组
      await axios.put(`http://localhost:5000/school/${selectedSchool.value._id}/add-user`, { userId }, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })

      alert('学校设置成功')
      closeDialog()
      router.push('/self') // 提交后返回用户信息页面
    } catch (error) {
      console.error('更新学校信息失败:', error)
      alert('更新学校信息失败')
    }
  }
}

// 关闭对话框
function closeDialog() {
  showDialog.value = false
  emit('update:modelValue', false) // 通知父组件更新状态
}

// 点击遮罩层关闭
function closeOnOverlay(event) {
  if (event.target.classList.contains('modal-overlay')) {
    closeDialog()
  }
}

// 监听ESC键关闭对话框
function handleKeyDown(event) {
  if (event.key === 'Escape' && showDialog.value) {
    closeDialog()
  }
}

// 点击外部关闭下拉菜单
function handleOutsideClick(event) {
  const searchContainer = document.querySelector('.search-container')
  if (searchContainer && !searchContainer.contains(event.target)) {
    showDropdown.value = false
  }
}

onMounted(() => {
  // 仅在显示对话框时加载数据
  if (showDialog.value) {
    fetchSchools()
  }
  document.addEventListener('keydown', handleKeyDown)
  document.addEventListener('click', handleOutsideClick)
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('click', handleOutsideClick)
})
</script>

<style scoped>
/* 遮罩层 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  transition: opacity 0.3s ease;
}

/* 弹窗容器 */
.modal-container {
  width: 500px;
  max-width: 90%;
  background-color: #1f1b24;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: modal-fade-in 0.3s ease forwards;
}

@keyframes modal-fade-in {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 弹窗头部 */
.modal-header {
  background-color: #121212;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #333333;
}

.modal-header h2 {
  margin: 0;
  color: #e0e0e0;
  font-size: 18px;
  font-weight: 600;
}

.close-button {
  background: none;
  border: none;
  color: #a0a0a0;
  font-size: 24px;
  cursor: pointer;
  line-height: 1;
  transition: color 0.3s ease;
}

.close-button:hover {
  color: #409EFF;
}

.close-button:focus {
  outline: none;
}

/* 弹窗内容 */
.modal-body {
  padding: 24px;
  color: #e0e0e0;
}

/* 搜索部分 */
.search-container {
  position: relative;
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  padding: 12px 40px 12px 12px;
  background-color: #2b2b2b;
  border: 1px solid #444444;
  border-radius: 4px;
  color: #e0e0e0;
  font-size: 16px;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #00aeff;
  box-shadow: 0 0 0 2px rgba(0, 170, 255, 0.2);
}

.search-input::placeholder {
  color: #a0a0a0;
}

.search-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #a0a0a0;
  pointer-events: none;
}

/* 下拉列表 */
.dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 300px;
  overflow-y: auto;
  background-color: #2b2b2b;
  border: 1px solid #444444;
  border-radius: 4px;
  margin-top: 5px;
  z-index: 10;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.school-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.school-item {
  padding: 12px 15px;
  cursor: pointer;
  color: #e0e0e0;
  transition: background-color 0.2s ease;
}

.school-item:hover {
  background-color: #444444;
}

/* 弹窗底部 */
.modal-footer {
  padding: 15px 20px 20px;
  text-align: center;
  border-top: 1px solid #444444;
}

.submit-button {
  padding: 12px 24px;
  background-color: #00aeff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 170, 255, 0.4);
}

.submit-button:hover {
  background-color: #33bbff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 170, 255, 0.5);
}

.submit-button:active {
  background-color: #0095e0;
  transform: translateY(0);
}

.submit-button:disabled {
  background-color: #333333;
  border: 1px solid #555555;
  color: #888888;
  cursor: not-allowed;
  box-shadow: none;
  transform: none;
}

.redirect-text {
  margin-top: 15px;
  color: #a0a0a0;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.3s ease;
}

.redirect-text:hover {
  color: #00aeff;
  text-decoration: underline;
}

/* 滚动条样式 */
.dropdown::-webkit-scrollbar {
  width: 8px;
}

.dropdown::-webkit-scrollbar-track {
  background-color: #333333;
}

.dropdown::-webkit-scrollbar-thumb {
  background-color: #555555;
  border-radius: 4px;
}

.dropdown::-webkit-scrollbar-thumb:hover {
  background-color: #666666;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .modal-container {
    width: 90%;
  }
}
</style>
